import { computed, ref } from 'vue'
import { useStore } from "vuex"
import { UserState } from "../../types/responseTypes";

export function useLogin() {
    const { state, dispatch, commit } = useStore()
    const hasLogIn = computed(() => state.user.hasLogIn)
    const avatar = computed(() => state.user.userInfo.avatar)
    const username = computed(() => state.user.userInfo.USERNAME)
    const ROLE_ID = computed(() => state.user.userInfo.ROLE_ID)
    const isFilledData = computed(() => state.user.isFilledData)
    const hasEnroll = computed(() => state.user.hasEnroll)

    function doLoginOrLogout() {
        console.log(hasLogIn.value)
        if (hasLogIn.value) {
            uni.showModal({
                title: '提示',
                content: '是否退出登录',
                success: ({ confirm }) => {
                    if (confirm) {
                        dispatch('logout')
                    }
                }
            })
            return
        }

        uni.getUserProfile({
            desc: '用于完善用户信息',
            success: async ({ userInfo }) => {
                try {
                    commit('SET_USER_INFO', {
                        avatar: userInfo.avatarUrl
                    })
                    const res = await dispatch('login')
                    if (res.STATE === UserState.START) {
                        commit('SET_USER_INFO', {
                            USERNAME: res.USERNAME
                        })
                    } else {
                        uni.showToast({
                            title: '账户已被停用',
                            icon: 'error',
                            mask: true
                        })
                    }

                } catch (err) {
                    setTimeout(() => {
                        uni.showModal({
                            title: '提示',
                            content: '当前微信用户没有绑定小程序用户，请前往注册用户或关联已用用户',
                            success: ({ confirm }) => {
                                if (confirm) {
                                    uni.navigateTo({
                                        url: '/pages/register/index'
                                    })
                                }
                            }
                        })
                    }, 100)
                }
            }
        })

    }

    return {
        hasLogIn,
        avatar,
        username,
        isFilledData,
        ROLE_ID,
        hasEnroll,
        doLoginOrLogout
    }
}
